# -*- coding: utf-8 -*-
import hashlib
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'mx_zhimin': {
        'API_KEY': '5LSiRMiK7Yf95RIrXV9kTKGFmYDBkhD1bn28bNwU21Uiyozjz82d3OCSKtIBu8PC1VgJLGzO5Y9SzXjj1cS7tmwUAWXQ29ZdA3PFFoAyncAlXwDgbQ3TCQQD5cHN2IuX',
    },
}

_QUERY_GATEWAY = 'http://222.73.234.146:18000/GW/gw.inter'
_GATEWAY = 'http://222.73.234.146:18000/GW/servlet/PayH5Servlet.do'
_WX_GATEWAY = 'http://ps.pushuapay.com:18000/GW/servlet/PayH5WServlet.do'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def verify_notify_sign(params, key):
    sign = params['hmac']
    params.pop('hmac')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("guofupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def check_notify_sign(request, mer_id):
    key = _get_api_key(mer_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("guofupay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['apporderid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('guofupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['tradesno']
    total_fee = float(data['realamount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0':  # 状态，0-成功，1-失败，3-处理中
        _LOGGER.info('guofupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def _gen_sign_str(parameter):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    return s[:len(s) - 1]


def generate_sign(parameter, key):
    s = _gen_sign_str(parameter)
    return _gen_sign(s + key)


def _get_pay_type(pay_type):
    if pay_type == 'wxpay':
        return "wxpay"
    else:
        return 'qq'


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _WX_GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    paytype = _get_pay_type(service)
    if paytype == 'qq':
        url = create_qq_charge(pay, pay_amount, info)
    else:
        url = create_wx_charge(pay, pay_amount, info)
    return {'charge_info': url}


def create_qq_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    mer_id = info['app_id']
    key = _get_api_key(mer_id)
    parameter_dict = OrderedDict((
        ("cmd", "PAYH5"),
        ("version", "2.0"),
        ("appid", mer_id),
        ("ordertime", time.strftime("%Y%m%d%H%M%S", time.localtime())),
        ("userid", 'CAT201801191336450003'),
        # ("userid", 'CUST_123456789'),
        ('apporderid', str(pay.id)),
        ('orderbody', 'charge'),
        ("amount", str(pay_amount)),
        ("biztype", 'qq'),
        ('pageyurl', '{}/pay/api/{}/guofupay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyurl', '{}/pay/api/{}/guofupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mer_id)),
    ))
    s = _gen_sign_str(parameter_dict)
    parameter_dict['hmac'] = _gen_sign(s + key)
    _LOGGER.info("guofupay create charge data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("guofupay create rsp data: %s %s", response.status_code, response.text)
    cache_id = redis_cache.save_html(pay.id, response.text)
    return settings.PAY_CACHE_URL + cache_id


def create_wx_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    mer_id = info['app_id']
    key = _get_api_key(mer_id)
    parameter_dict = OrderedDict((
        ("cmd", "PAYH5WECHAT"),
        ("version", "2.0"),
        ("appid", mer_id),
        ("ordertime", time.strftime("%Y%m%d%H%M%S", time.localtime())),
        ("userid", 'CAT201801191336450003'),
        ('apporderid', str(pay.id)),
        ('orderbody', 'charge'),
        ('orderdesc', 'charge'),
        ("amount", str(pay_amount)),
        ("acquirertype", 'wechat'),
        ("sceneinfotype", 'wap'),
        ('sceneinfobody', settings.NOTIFY_PREFIX),
        ('sceneinfoname', 'charge'),
        ('notifyurl', '{}/pay/api/{}/guofupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mer_id)),
    ))
    s = _gen_sign_str(parameter_dict)
    parameter_dict['hmac'] = _gen_sign(s + key)
    _LOGGER.info("guofupay sign str: %s", s + key)
    _LOGGER.info("guofupay create wx charge data: %s", parameter_dict)
    cache_id = redis_cache.save_html(pay.id, _build_form(parameter_dict))
    return settings.PAY_CACHE_URL + cache_id


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ("cmd", "QUERYORDERINFO"),
        ("version", "2.0"),
        ("appsno", "1"),
        ("appid", app_id),
        ("userid", str(pay_id)[-6:]),
        ('apporderid', str(pay_id)),
    ))
    s = _gen_sign_str(parameter_dict)
    parameter_dict['hmac'] = _gen_sign(s + api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('guofupay query response, status_code: %s, txt: ', response.status_code, response.text)
    if response.status_code == 200:

        trade_status = _get_str(response.text, 'errcode=', '&')
        trade_no = ''
        total_fee = float(_get_str(response.text, 'realamount=', '&'))

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0:成功1：失败，3：处理中等待通知或查询
        if trade_status == '0':
            _LOGGER.info('guofupay query order success, pay_id:%s' % pay_id)
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('guofupay data error, status_code: %s', response.status_code)
